#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>


void Tips()
{
    printf("Format: ./http_server [ip] [port]\n");
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Tips();
        return 1;
    }

    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock_fd < 0)
    {
        perror("socket fail");
        return 1;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(atoi(argv[2]));

    int ret = bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0)
    {
        perror("Bind Fail");
        return 1;
    }

    ret = listen(sock_fd, 10);
    if(ret < 0)
    {
        perror("listen fail");
        return -1;
    }

    while(1)
    {
        struct sockaddr_in client_addr;
        socklen_t len;
        int client_fd = accept(sock_fd, (struct sockaddr*)&client_addr, &len);
        if(client_fd < 0)
        {
            perror("accept fail");
            continue;
        }

        char buff[1024];
        ssize_t read_size = read(client_fd, buff, sizeof(buff) - 1);
        if(read_size < 0)
        {
            return 1;
        }
        printf("[Request]:%s", buff);


        char rbuff[1024];
        const char* content = "hello world!";
        sprintf(rbuff, "HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s", strlen(content), content);
        write(client_fd, rbuff, strlen(rbuff));
    }
    return 0;
}
